package com.github.chirspan.xaas.uc.web.api;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.chirspan.xaas.api.BaseCRUDRestController;
import com.github.chirspan.xaas.core.rest.RestResult;
import com.github.chirspan.xaas.core.util.HeaderSecurityUtils;
import com.github.chirspan.xaas.rbac.config.SecurityProperties;
import com.github.chirspan.xaas.rbac.model.RbacUser;
import com.github.chirspan.xaas.uc.service.IRbacUserService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * ************************
 * <p>用户管理API</p>
 * *************************
 *
 * @author chenpan
 * @date 2021/1/20 11:01
 */
@RestController
@RequestMapping("user")
public class RbacUserController extends BaseCRUDRestController<RbacUser> {

    @Autowired
    private IRbacUserService userService;
    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public RestResult pageList(@ApiParam("查询条件实体") RbacUser user,
                               @ApiParam("页码") @RequestParam(name = "pageNo", required = false, defaultValue = "1")
                                       Integer pageNo,
                               @ApiParam("每页数量") @RequestParam(name = "pageSize", required = false, defaultValue = "10")
                                       Integer pageSize) throws IllegalAccessException {
        pageNo = pageNo == null ? 1 : pageNo;
        pageSize = pageSize == null ? 10 : pageSize;
        Page<RbacUser> page = new Page<>(pageNo, pageSize);
        IPage<RbacUser> pageInfo = userService.getUserAndRole(page, user);
        return RestResult.OK(pageInfo);
    }

    @Override
    public RestResult add(@ApiParam("新增实体") @RequestBody @Validated RbacUser user,
                          BindingResult result) {
        user.setPassword(securityProperties.getDefaultPasswd());
        user.setCreateBy(HeaderSecurityUtils.getUserName());
        userService.addUser(user);
        return RestResult.OK(user.getId(), "新增成功");
    }

    @Override
    public RestResult update(@PathVariable("id") String id,
                             @RequestBody @Validated RbacUser user,
                             BindingResult result) {
        user.setUpdateBy(HeaderSecurityUtils.getUserName());
        user.setUpdateTime(new Date());
        user.setUpdateCount(user.getUpdateCount() == null ? 0 : user.getUpdateCount() + 1);
        userService.updateUser(user);
        return RestResult.OK(id, "更新成功");
    }

    @Override
    public RestResult delete(@PathVariable("id") String id) {
        userService.deleteUser(id);
        return RestResult.OK(id, "删除成功");
    }
}